﻿using ExchangeClient.Abstractions.Model;
using ExchangeClient.Abstractions;
using SyncService.Abstractions.Services;
using System;
using System.Collections.Generic;
using System.Composition;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SyncService.Core.Model;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Runtime.InteropServices;
using SyncService.Common;
using NPOI.XSSF.UserModel;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging;
using HKH.Common;
using Microsoft.VisualBasic;
using NPOI.HPSF;
using System.Diagnostics;
using static ICSharpCode.SharpZipLib.Zip.ExtendedUnixData;
using System.Web;
using NPOI.SS.Formula.Functions;
using Org.BouncyCastle.Crypto;

namespace SyncService.Core.Services
{


    [Export(typeof(ISyncService))]
    [ExportMetadata(YdConstants.ID, "Asset")]
    public class AssetService : SyncServiceBase
    {
        protected override string NotifyGroupName => "";
        private ILogger<AssetService> _logger = null;

        private bool IsNotPush = false;
        //private Dictionary<string,string> companyData = new Dictionary<string,string>();
        private Dictionary<string, string> centerData = new Dictionary<string, string>();
        private Dictionary<string, Guid> assetInStorageData = new Dictionary<string, Guid>();
        public AssetService() : base(YdConstants.YIDEA, "mysqlcache", "")
        {
        }
        protected override void InitializeContext()
        {
            base.InitializeContext();
            _logger = Resolver.Resolve<ILogger<AssetService>>();
        }
        public override void Execute(dynamic? state)
        {
            //var company = UserDefines.First(x => x.Name == "公司主数据");
            var center = UserDefines.First(x => x.Name == "成本中心");
            var companyMasterCodeField = ExtendFields.First(x => x.ObjectType == 51 && x.Name == "公司代码");
            var companyMasterNameField = ExtendFields.First(x => x.ObjectType == 51 && x.Name == "公司名称");

            var centerMasterCodeField = ExtendFields.First(x => x.ObjectType == 52 && x.Name == "成本中心");
            var centerMasterNameField = ExtendFields.First(x => x.ObjectType == 52 && x.Name == "成本中心名称");
            try
            {
                _logger.LogInformation("开始处理批量资产数据");
                RequestData requestData = state;
                List<AssetMaster> data = JsonSerializer.Deserialize<List<AssetMaster>>(requestData.Body);
                _logger.LogInformation("资产数量：" + data.Count);

                Asset asset = new Asset();
                asset.ExtraData = new JsonObject
                {
                    ["AssetMaster"] = requestData.Body
                };
                JsonObject result = ToClient.AddAsset(asset);//插入sap资产表
                if (result["IsComplete"].ToString() == "true")//最后一次推送
                {
                    var synchronousTime = DateTime.Now.ToString("yyyy-MM-dd");


                    //更新资产
                    #region 更新资产
                    JsonObject updateResult = ToClient.GetData(new JsonObject { ["Flag"] = 2 });
                    if (updateResult["assetArray"] != null && updateResult["assetArray"]!.ToString() != "")
                    {
                        int sapCount = int.Parse(updateResult["sapCount"].ToString());
                        List<AssetCallBackData> assetCallBackDatas = new List<AssetCallBackData>();
                        List<AssetMaster> updateData = JsonSerializer.Deserialize<List<AssetMaster>>(updateResult["assetArray"]!.ToString())!;
                        int updateCount = updateData.Count;
                        string diffCount = updateResult["diffCount"].ToString();
                        int errorCount = 0;

                        var timer = new Stopwatch();
                        timer.Start();
                        try
                        {
                            var timer1 = new Stopwatch();
                            timer1.Start();
                            var date1 = DateTime.Now;
                            if (date1.Hour >= 20 && date1.Hour < 23)
                            {
                                _logger.LogInformation("到时间要休息了~");
                                //在八点的时间点，休眠3小时
                                var reciveTime = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd 23:00:00"));
                                TimeSpan timeSpan = reciveTime - DateTime.Now;
                                int hour = 60 * Convert.ToInt32(Math.Round(timeSpan.TotalMinutes));
                                Thread.Sleep(hour * 1000);
                                _logger.LogInformation("休息结束了~");
                            }
                            _logger.LogInformation("开始拉取公司，成本中心数据");
                            #region 拉取公司，成本中心数据
                            //var companyList = YideaClient.GetCustomizedFormDatas(formId: company.Id, new QueryParam() { }).ToList();
                            //ConvertCompanyToDic(companyList);
                            var centerlist = YideaClient.GetCustomizedFormDatas(formId: center.Id, new QueryParam() { }).ToList();
                            ConvertCenterToDic(centerlist);
                            #endregion
                            //拉取入库单
                            List<GetAssetInStorage> assetinStorages = YideaClient.GetAssetInStorages(null).ToList();
                            ConvertGetAssetInStorageToDic(assetinStorages);

                            timer1.Stop();
                            _logger.LogInformation($"拉取公司，成本中心结束，共花费{timer1.ElapsedMilliseconds}");

                            var insertAssets = new List<Asset>();
                            var updateAssets = new List<Asset>();

                            var page = 0;
                            var perPage = 100;
                            var getAssetsBarcodes = updateData.Select(e => e.BarCode).Skip(page * perPage).Take(perPage).ToList();
                            while (getAssetsBarcodes.Any())
                            {
                                var date = DateTime.Now; 
                                if (date.Hour >= 20 && date.Hour < 23)
                                {
                                    _logger.LogInformation("到时间要休息了~");
                                    //在八点的时间点，休眠3小时
                                    var reciveTime = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd 23:00:00"));
                                    TimeSpan timeSpan = reciveTime - DateTime.Now;
                                    int hour = 60 * Convert.ToInt32(Math.Round(timeSpan.TotalMinutes));
                                    Thread.Sleep(hour * 1000);
                                    _logger.LogInformation("休息结束了~");
                                }
                                _logger.LogInformation("当前处理的资产条数：" + page * perPage);
                                var yideaExistingAssetsRes = YideaClient.GetAssets(new QueryParam
                                {
                                    FilterString = $"orderby=-id&requireHierarchies=1&filterByPermission=1&barcodeIn={string.Join(",", getAssetsBarcodes)}"
                                });
                                var list = yideaExistingAssetsRes.ToList();
                                WriteOldData(list);
                                var activeList = list.Where(x => x.State != 4).ToList();
                                var scrapList = list.Where(x => x.State == 4).ToList();




                                //MasterDataFillAssetResultViewModel masterDataFillAssetResult = MasterDataFillAssetTask(activeList, updateData);
                                //insertAssets.AddRange(masterDataFillAssetResult.inseAssetMasterrtAssets);
                                _logger.LogInformation("开始赋值");
                                #region 赋值
                                //尝试做并发
                                List<Task<MasterDataFillAssetResultViewModel>> tasks = new List<Task<MasterDataFillAssetResultViewModel>>();
                                var taskPerPage = 10;
                                var keyCount = activeList.Count;
                                var pageCount = keyCount % taskPerPage > 0 ? (keyCount / taskPerPage) + 1 : (keyCount / taskPerPage);

                                for (var i = 0; i < pageCount; i++)
                                {
                                    var items = activeList.Skip(i * taskPerPage).Take(taskPerPage).ToList();
                                    var tk =
                                        Task.Run<MasterDataFillAssetResultViewModel>(
                                                delegate
                                                {
                                                    return MasterDataFillAssetTask(
                                                     items,
                                                     updateData
                                                    );
                                                });
                                    tasks.Add(tk);
                                }

                                var tResult = Task.WhenAll(tasks.ToArray());
                                tResult.Wait();
                                foreach (var t in tasks)
                                {
                                    insertAssets.AddRange(t.Result.insertAssets);
                                }
                                #endregion

                                if (insertAssets.Count() >= 3000)
                                {
                                    var isSuccess = ImportAssets(insertAssets);
                                    if (!string.IsNullOrEmpty(isSuccess))
                                    {
                                        errorCount = errorCount + insertAssets.Count();
                                        insertAssetCallBackData(insertAssets, assetCallBackDatas, 2, isSuccess);
                                    }
                                    insertAssets = new List<Asset>();
                                }

                                #region 报废进错误信息
                                errorCount = errorCount + scrapList.Count;
                                insertAssetCallBackData(scrapList, assetCallBackDatas, 1);

                                #endregion


                                page++;
                                getAssetsBarcodes = updateData.Select(e => e.BarCode).Skip(page * perPage).Take(perPage).ToList();
                            }

                            if (insertAssets.Count() > 0)
                            {
                                var isSuccess = ImportAssets(insertAssets);
                                if (!string.IsNullOrEmpty(isSuccess))
                                {
                                    errorCount = errorCount + insertAssets.Count();
                                    insertAssetCallBackData(insertAssets, assetCallBackDatas, 2, isSuccess);
                                }
                                insertAssets = new List<Asset>();
                            }





                        }
                        catch (Exception ex)
                        {
                            _logger.LogError(ex, "批量处理资产更新--发生异常");
                            assetCallBackDatas.Add(new AssetCallBackData()
                            {
                                Date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                                BarCode = "",
                                FinancialCode = "",
                                Msg = "系统异常，联系管理员：" + ex.ToString()
                            });
                        }

                        timer.Stop();
                        _logger.LogInformation($"同步任务结束，共花费{timer.ElapsedMilliseconds}");


                        string exportFile = "";
                        if (assetCallBackDatas.Count > 0)
                        {
                            exportFile = ExportToString(assetCallBackDatas);
                        }
                        var domainNameField = ExtendFields.First(e => e.Name == "域名" && e.ObjectType == 0);
                        string fullFile = exportFile == "" ? "" : domainNameField.FieldId + exportFile;
                        WriteToForm(synchronousTime, sapCount, diffCount, updateCount, errorCount, fullFile);

                    }
                    #endregion

                }
                _logger.LogInformation("结束处理批量资产数据");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "批量处理资产发生异常");
            }

        }
        private void insertAssetCallBackData(List<Asset> assets, List<AssetCallBackData> assetCallBackDatas, int flag, string message = "")
        {
            var financialCodeField = ExtendFields.FirstOrDefault(x => x.ObjectType == 0 && x.Name.Equals("财务资产编码"));

            assets.ForEach(item => {
                string financialCode = "";
                if (!string.IsNullOrEmpty(item.DataJson))
                {
                    var datajson = item.DataJson;
                    var dataJsonParse = JsonNode.Parse(datajson)!.AsObject();
                    financialCode = dataJsonParse[financialCodeField.FieldId]?.ToString();
                }

                assetCallBackDatas.Add(new AssetCallBackData()
                {
                    Date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                    BarCode = item.Barcode,
                    FinancialCode = financialCode,
                    Msg = flag == 1 ? "资产已报废" : "更新失败：" + message
                });


            });
        }
        private string ImportAssets(List<Asset> assets)
        {

            var json = JsonSerializer.Serialize(new { InsertAssets = new List<Asset>(), UpdateAssets = assets });
            _logger.LogInformation("本次更新资产：" + json);
            WriteImportUpdateData(json);

            var errorMsg = string.Empty;
            var resItems = YideaClient.ImportAssetsWithoutValidation(json);
            if (!resItems.isSuccess)//失败全失败
            {
                _logger.LogError("本次更新资产失败");
                return resItems.errorMsg;
            }
            else
            {
                //检查导入任务进度
                var taskId = resItems.res!["id"]?.GetValue<string>();
                var importProgress = YideaClient.GetImportProgress(taskId, 120);
                if (!importProgress.isSuccess)
                {
                    _logger.LogError("本次更新资产失败");
                    return importProgress.errorMsg;
                }
                else
                {
                    _logger.LogInformation("本次更新资产成功");
                    return "";
                }
            }
        }
        private void ConvertCompanyToDic(List<CustomizedFormData> datas)
        {
            var companyMasterCodeField = ExtendFields.First(x => x.ObjectType == 51 && x.Name == "公司代码");
            foreach (var data in datas)
            {
                var custmerData = JsonSerializer.Serialize(data.Data);
                JsonObject companyDataJson = JsonNode.Parse(data.Data["dataJson"].ToString()).AsObject();
                var key = companyDataJson[companyMasterCodeField.FieldId].ToString();
                //if (companyData.ContainsKey(key))
                //{
                //    continue;
                //}
                //else
                //{
                //    companyData.Add(key, custmerData);
                //}
            }
        }
        private void ConvertGetAssetInStorageToDic(List<GetAssetInStorage> getAssetInStorages)
        {
            foreach (var assetInStorage in getAssetInStorages)
            {
                var key = assetInStorage.SerialNo;
                if (assetInStorageData.ContainsKey(key))
                {
                    continue;
                }
                else
                {
                    assetInStorageData.Add(key, assetInStorage.Id);
                }
            }
        }
        private void ConvertCenterToDic(List<CustomizedFormData> datas)
        {
            var centerMasterCodeField = ExtendFields.First(x => x.ObjectType == 52 && x.Name == "成本中心");
            foreach (var data in datas)
            {
                var custmerData = JsonSerializer.Serialize(data.Data);
                JsonObject companyDataJson = JsonNode.Parse(data.Data["dataJson"].ToString()).AsObject();
                var key = companyDataJson[centerMasterCodeField.FieldId].ToString();
                if (centerData.ContainsKey(key))
                {
                    continue;
                }
                else
                {
                    centerData.Add(key, custmerData);
                }
            }
        }
        private MasterDataFillAssetResultViewModel MasterDataFillAssetTask(List<Asset> updateAsset, List<AssetMaster> assetMasters)
        {
            List<Asset> assetList = new List<Asset>();
            #region 字段
            var financialCodeField = ExtendFields.FirstOrDefault(x => x.ObjectType == 0 && x.Name.Equals("财务资产编码"));
            //var companyCodeField = ExtendFields.FirstOrDefault(x => x.ObjectType == 0 && x.Name.Equals("公司代码"));
            var originalValueField = ExtendFields.FirstOrDefault(x => x.ObjectType == 0 && x.Name.Equals("资产原值"));
            var lJZJField = ExtendFields.FirstOrDefault(x => x.ObjectType == 0 && x.Name.Equals("累计折旧"));

            var capitalizationDateField = ExtendFields.FirstOrDefault(x => x.ObjectType == 0 && x.Name.Equals("本金化日期"));
            var scrapDateField = ExtendFields.FirstOrDefault(x => x.ObjectType == 0 && x.Name.Equals("报废日期"));
            var centerCodeField = ExtendFields.FirstOrDefault(x => x.ObjectType == 0 && x.Name.Equals("成本中心码"));
            var zJDateField = ExtendFields.FirstOrDefault(x => x.ObjectType == 0 && x.Name.Equals("折旧开始日"));
            var useYearField = ExtendFields.FirstOrDefault(x => x.ObjectType == 0 && x.Name.Equals("使用年"));
            var useMonthField = ExtendFields.FirstOrDefault(x => x.ObjectType == 0 && x.Name.Equals("使用月"));
            var zJCodeField = ExtendFields.FirstOrDefault(x => x.ObjectType == 0 && x.Name.Equals("折旧码"));
            var IsDeferField = ExtendFields.FirstOrDefault(x => x.ObjectType == 0 && x.Name.Equals("是否递延"));

            //var companyNameField = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "公司名");
            var centerNameField = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "成本中心名");

            //var assetComapnyField = ExtendFields.FirstOrDefault(x => x.ObjectType == 0 && x.Name.Equals("公司名称"));
            var assetCenterField = ExtendFields.FirstOrDefault(x => x.ObjectType == 0 && x.Name.Equals("成本中心名称"));

            var assetAmountField = ExtendFields.FirstOrDefault(x => x.ObjectType == 0 && x.Name.Equals("资产净值"));
            var periodsNumField = ExtendFields.FirstOrDefault(x => x.ObjectType == 0 && x.Name.Equals("已提期数"));

            var companyMasterCodeField = ExtendFields.First(x => x.ObjectType == 51 && x.Name == "公司代码");
            var companyMasterNameField = ExtendFields.First(x => x.ObjectType == 51 && x.Name == "公司名称");

            var centerMasterCodeField = ExtendFields.First(x => x.ObjectType == 52 && x.Name == "成本中心");
            var centerMasterNameField = ExtendFields.First(x => x.ObjectType == 52 && x.Name == "成本中心名称");

            //var company = UserDefines.First(x => x.Name == "公司主数据");
            //var center = UserDefines.First(x => x.Name == "成本中心");
            UserDefine userDefine = UserDefines.First(x => x.Name == "资产主数据");
            var involvedCodeField = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "发票号码");
            var transferDateField = ExtendFields.FirstOrDefault(x => x.ObjectType == 0 && x.Name == "调拨时间");
            #endregion

            foreach (var assetInfo in updateAsset)
            {
                try 
                {
                    var createdate = DateTime.Parse(assetInfo.CreatedDate);
                    var date = createdate.AddHours(8);
                    assetInfo.PurchasedDate = DateTime.Parse(assetInfo.PurchasedDate).AddHours(8).ToString("yyyyMMdd HH:mm:ss");
                    assetInfo.CreatedDate = date.ToString("yyyyMMdd HH:mm:ss");
                    _logger.LogInformation("MaintenanceExpiredDate");
                    if (!string.IsNullOrEmpty(assetInfo.MaintenanceExpiredDate)) {
                        assetInfo.MaintenanceExpiredDate=DateTime.Parse(assetInfo.MaintenanceExpiredDate).AddHours(8).ToString("yyyyMMdd HH:mm:ss");
                    }
                    var asdsadas = assetMasters.Where(e => e.BarCode == assetInfo.Barcode);
                    if (asdsadas.Count()==1)
                    {
                        AssetMaster? dataItem = assetMasters.Where(e => e.BarCode == assetInfo.Barcode).FirstOrDefault();
                        if (!string.IsNullOrEmpty(assetInfo.PurchaseReceiveSerialNo))
                        {
                            assetInfo.PurchaseReceiveDetailId = assetInStorageData[assetInfo.PurchaseReceiveSerialNo];
                        }
                        _logger.LogInformation("assetInfo.DataJson:" + assetInfo.DataJson);
                        if (assetInfo != null && !string.IsNullOrEmpty(assetInfo.DataJson))
                        {


                            //JsonObject companyDetail = new JsonObject();\
                            //var companyJson = "";
                            //companyData.TryGetValue(dataItem.CompanyCode, out companyJson);

                            //string companyName = "";
                            //if (!string.IsNullOrEmpty(companyJson))
                            //{
                            //    companyDetail = JsonNode.Parse(companyJson).AsObject();
                            //    JsonObject companyDataJson = JsonNode.Parse(companyDetail["dataJson"].ToString()).AsObject();
                            //    companyDetail[companyMasterNameField.FieldId] = companyDataJson[companyMasterNameField.FieldId].ToString();
                            //    companyName = companyDataJson[companyMasterNameField.FieldId].ToString();
                            //    companyDetail.Remove("dataJson");
                            //    companyDetail[companyMasterCodeField.FieldId] = dataItem.CompanyCode;
                            //}

                            JsonObject centerDetail = new JsonObject();
                            var centerJson = "";
                            centerData.TryGetValue(dataItem.CenterCode, out centerJson);
                            string centerName = "";
                            if (!string.IsNullOrEmpty(centerJson))
                            {
                                centerDetail = JsonNode.Parse(centerJson).AsObject();
                                JsonObject centerDataJson = JsonNode.Parse(centerDetail["dataJson"].ToString()).AsObject();
                                centerDetail[assetCenterField.FieldId] = centerDataJson[centerMasterNameField.FieldId].ToString();
                                centerName = dataItem.CostCenterName;
                                centerDetail.Remove("dataJson");
                                centerDetail[centerMasterCodeField.FieldId] = dataItem.CenterCode;
                            }
                            _logger.LogInformation("成本中心的json"+ centerDetail);
                            var datajsonNew = assetInfo.DataJson;
                            _logger.LogInformation("assetInfo.DataJson2:" + datajsonNew);
                            var index = datajsonNew.IndexOf(involvedCodeField.FieldId);
                            var lasetindex = datajsonNew.LastIndexOf(involvedCodeField.FieldId);
                            if (index != lasetindex)
                            {
                                datajsonNew = datajsonNew.Substring(0, index) + datajsonNew.Substring(lasetindex, datajsonNew.Length - lasetindex);
                            }
                            _logger.LogInformation("assetInfo.DataJson3:" + index + "," + lasetindex);
                            var dataJson = JsonNode.Parse(datajsonNew)!.AsObject();
                            _logger.LogInformation("assetInfo.DataJson4:" + dataJson);
                            var transferDateFromJson = dataJson[transferDateField.FieldId]?.ToString();
                            if (!string.IsNullOrEmpty(transferDateFromJson))
                            {
                                if (transferDateFromJson.IndexOf('-') < 0)
                                {
                                    var transferDate = (transferDateFromJson).StampToDateTime();
                                    dataJson[transferDateField.FieldId] = transferDate.ToString("yyyy-MM-dd 00:00:00");
                                }
                            }
                            _logger.LogInformation("步骤1");
                            dataJson.SetValue(financialCodeField!, dataItem.FinancialCode);
                            _logger.LogInformation("步骤2");
                            //dataJson.SetValue(companyCodeField!, dataItem.CompanyCode);

                            dataJson[lJZJField.FieldId] = dataItem.LJZJ;
                            _logger.LogInformation("步骤3");

                            dataJson.SetValue(originalValueField!, dataItem.OriginalValue);
                            _logger.LogInformation("步骤4");
                            var capitalizationDate = dataItem.CapitalizationDate;
                            if (!string.IsNullOrEmpty(capitalizationDate))
                            {
                                capitalizationDate = DateTime.Parse(capitalizationDate).ToString("yyyy-MM-dd 00:00:00");
                            }
                            _logger.LogInformation("步骤5");
                            dataJson[capitalizationDateField.FieldId] = capitalizationDate;
                            _logger.LogInformation("步骤6");
                            var scrapDate = dataItem.ScrapDate;
                            if (!string.IsNullOrEmpty(scrapDate))
                            {
                                scrapDate = DateTime.Parse(scrapDate).ToString("yyyy-MM-dd 00:00:00");
                            }
                            _logger.LogInformation("步骤7");
                            dataJson[scrapDateField.FieldId] = scrapDate;
                            dataJson.SetValue(centerCodeField!, dataItem.CenterCode);
                            var zJDate = dataItem.ZJDate;
                            if (!string.IsNullOrEmpty(zJDate))
                            {
                                zJDate = DateTime.Parse(zJDate).ToString("yyyy-MM-dd 00:00:00");
                            }
                            _logger.LogInformation("步骤8");
                            dataJson.SetValue(zJDateField!, zJDate);

                            _logger.LogInformation("步骤9");
                            dataJson.SetValue(useYearField!, dataItem.UseYear);
                            dataJson.SetValue(useMonthField!, dataItem.UseMonth);
                            dataJson.SetValue(zJCodeField!, dataItem.ZJCode);
                            dataJson.SetValue(IsDeferField!, dataItem.IsDefer);
                            dataJson.SetValue(centerNameField!, dataItem.CostCenterName);
                            _logger.LogInformation("步骤10");
                            var originalValue = "0.0";
                            if (!string.IsNullOrEmpty(dataItem.OriginalValue))
                            {
                                originalValue = dataItem.OriginalValue;
                            }
                            assetInfo.Amount = decimal.Parse(originalValue);
                            var ljzj = "0.0";
                            if (!string.IsNullOrEmpty(dataItem.LJZJ))
                            {
                                ljzj = dataItem.LJZJ;
                            }
                            _logger.LogInformation("步骤11");
                            var amount = (decimal.Parse(originalValue) + decimal.Parse(ljzj));
                            dataJson[assetAmountField.FieldId] = amount;
                            _logger.LogInformation("步骤12");
                            dataJson[periodsNumField.FieldId] = (dataItem.NumBeRaised); //DifferMonth(dataItem.ZJDate);
                            _logger.LogInformation("步骤13");
                            //dataJson[companyNameField.FieldId] = (companyName.ToString());
                            //dataJson[centerNameField.FieldId] = (centerName.ToString());
                            //dataJson[assetComapnyField.FieldId] = companyDetail;
                            //dataJson[assetCenterField.FieldId] = centerDetail;
                            assetInfo.DataJson = JsonSerializer.Serialize(dataJson);
                            _logger.LogInformation("步骤14");
                            assetInfo.ExtraData = null;
                            assetInfo.ExtensionFields = null;
                            _logger.LogInformation("assetInfo现在里面的数据都有什么" + assetInfo);
                            _logger.LogInformation("步骤15");
                        }
                        _logger.LogInformation("是否递延"+ dataItem.IsDefer);
                        _logger.LogInformation("赋值的数据"+assetInfo);
                        assetList.Add(assetInfo);
                        _logger.LogInformation("步骤16");
                    }
                    else if(asdsadas.Count() > 1)
                    {
                        _logger.LogError("数据发生异常,请检查数据");
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "批量塞数据发生异常" + ex.ToString());

                }

            }

            return new MasterDataFillAssetResultViewModel() { insertAssets = assetList };
        }

        public class MasterDataFillAssetResultViewModel
        {
            public List<Asset> insertAssets { get; set; }
        }
        private void WriteToForm(string syncTime, int sapCount, string diffCount, int updateCount, int errorCount, string fileName)
        {
            var tjFormField = UserDefines.First(e => e.Name == "同步资产结果统计");

            var tjDateField = ExtendFields.First(e => e.Name == "同步日期" && e.ObjectType == 56);
            var sapCountField = ExtendFields.First(e => e.Name == "sap资产数" && e.ObjectType == 56);
            var diffCountField = ExtendFields.First(e => e.Name == "差异数量" && e.ObjectType == 56);
            var updateCountField = ExtendFields.First(e => e.Name == "更新数量" && e.ObjectType == 56);
            var errorCountField = ExtendFields.First(e => e.Name == "失败数量" && e.ObjectType == 56);
            var fileLinkField = ExtendFields.First(e => e.Name == "明细地址" && e.ObjectType == 56);
            CustomizedFormData tjForm = new CustomizedFormData();
            tjForm.StartWorkflow = false;
            tjForm.TriggerRobot = false;
            tjForm.FormId = tjFormField.Id;
            tjForm.Data = new JsonObject
            {
                [tjDateField.FieldId] = new JsonObject
                {
                    ["value"] = syncTime
                },
                [sapCountField.FieldId] = new JsonObject
                {
                    ["value"] = sapCount
                },
                [diffCountField.FieldId] = new JsonObject
                {
                    ["value"] = diffCount
                },
                [updateCountField.FieldId] = new JsonObject
                {
                    ["value"] = updateCount
                },
                [errorCountField.FieldId] = new JsonObject
                {
                    ["value"] = errorCount
                },
                [fileLinkField.FieldId] = new JsonObject
                {
                    ["value"] = fileName
                }
            };
            bool addResult = YideaClient.AddNewCustomizedFormData(tjForm);

        }
        private int DifferMonth(string date)
        {
            var predate = DateTime.Parse(date);
            var months = ((DateTime.Now.Year - predate.Year) * 12) + DateTime.Now.Month - predate.Month;
            return months;
        }
        public void WriteOldData(List<Asset> assets) 
        {
            var fileName = DateTime.Now.ToString("yyyyMMddHHmmssffff");
            var target = Path.Combine(SyncService.Common.Constants.WebRootPath, "OldData", $"{fileName}原始数据备份.json");
            try
            {
                // 提取文件夹路径（去掉文件名）
                string directoryPath = Path.GetDirectoryName(target);
                if (!Directory.Exists(directoryPath))
                {
                    Directory.CreateDirectory(directoryPath);
                    _logger.LogInformation("创建文件夹: {Directory}", directoryPath);
                }
                var mdJson = JsonSerializer.Serialize(assets);
                System.IO.File.WriteAllText(target, mdJson);
            }
            catch (Exception ex)
            {
                _logger.LogInformation(ex, "写入文件失败: {File}", target);
                throw new InvalidOperationException("文件写入失败，请检查路径和权限", ex);
            }
          
        }
        public void WriteImportUpdateData(string mdJson)
        {
            var fileName = DateTime.Now.ToString("yyyyMMddHHmmssffff");
            var target = Path.Combine(SyncService.Common.Constants.WebRootPath, "ImportUpdateData", $"{fileName}批量更新数据.json");
            
            var ss = 11;
            try
            {
                // 提取文件夹路径（去掉文件名）
                string directoryPath = Path.GetDirectoryName(target);
                // 检查并创建文件夹（如果不存在）
                if (!Directory.Exists(directoryPath))
                {
                    Directory.CreateDirectory(directoryPath);
                    _logger.LogInformation("创建文件夹: {ImportUpdateData}", directoryPath);
                }
                System.IO.File.WriteAllText(target, mdJson);

            }
            catch (Exception ex)
            {

                _logger.LogError(ex, "写入文件失败: {ImportUpdateData}", target);
                // 抛出自定义异常或返回错误
                throw new InvalidOperationException("文件写入失败，请检查路径和权限", ex);
            }
           
        }
        public string ExportToString(List<AssetCallBackData> assetExportViewModels)
        {
            _logger.LogInformation("开始导出资产回写情况统计excel~");
            var template = Path.Combine(SyncService.Common.Constants.WebRootPath, "Templates", "资产回写情况统计.xlsx");
            var fileName = DateTime.Now.ToString("yyyyMMddHHmmssffff");
            var target = Path.Combine(SyncService.Common.Constants.WebRootPath, "temp", $"{fileName}资产回写情况统计.xlsx");

            System.IO.File.Copy(template, target);
            FileStream file = new FileStream(target, FileMode.Open, FileAccess.Read);
            var workbook = new XSSFWorkbook(file);
            var sheet = workbook.GetSheet("资产回写情况统计");
            int rowIndex = sheet.LastRowNum + 1;

            foreach (var item in assetExportViewModels)
            {

                XSSFRow dataRow = (XSSFRow)sheet.CreateRow(rowIndex);
                dataRow.CreateCell(0).SetCellValue(item.Date);
                dataRow.CreateCell(1).SetCellValue(item.BarCode);
                dataRow.CreateCell(2).SetCellValue(item.FinancialCode);
                dataRow.CreateCell(3).SetCellValue(item.Msg);
                ++rowIndex;
            }

            using (var stream = new FileStream(target, FileMode.Create, FileAccess.Write))
            {
                workbook.Write(stream);
            }
            _logger.LogInformation("生成excel");
            _logger.LogInformation(target);
            //string base64 = FileToBase64String.FileToBase64(target);
            return "/temp/" + fileName + "资产回写情况统计.xlsx";
        }
    }
}
